/*
 * Writed by Alexey Matveev 
 * Original tutorial:
 * https://ravesli.com/urok-6-tekstury-v-opengl/
 */
#include <render/output/texture.h>

#define STB_IMAGE_IMPLEMENTATION
#include <app/modules/thirdParty/stb_image.h>

#include <GLES3/gl3.h>
#include <cassert>
#include <iostream>

Texture::Texture ( const std::string &filename, ATextureFilterType filterType ) {
    
    unsigned char* data = stbi_load ( filename.c_str (), &width, &height, &nrChannels, 0 );
    
    if ( data == NULL ) {
        std::cerr << "Texture loading failed: " << filename << std::endl;
    }
    
    glGenTextures ( 1, &texture ); //arg: count, object of type unsigned int
    glBindTexture ( GL_TEXTURE_2D, texture ); //using current texture
    
    glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    
    if ( filterType == ATexFilter_Linear ) {
        glTexParameterf ( GL_TEXTURE_2D,  GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameterf ( GL_TEXTURE_2D,  GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    } else if ( filterType == ATexFilter_Near ) {
        glTexParameterf ( GL_TEXTURE_2D,  GL_TEXTURE_MIN_FILTER, GL_NEAREST );
        glTexParameterf ( GL_TEXTURE_2D,  GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    }
    
    glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
    glGenerateMipmap ( GL_TEXTURE_2D );
    
    stbi_image_free ( data );
}

void Texture::Bind () {

    glBindTexture ( GL_TEXTURE_2D, texture );
}


Texture::~Texture () {
    glDeleteTextures ( 1, &texture );
}
